package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    //依赖注入
    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1.参数检验（用户登录，检验文件格式（。jpg,.png,....））
        if (multipartFile==null || multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //2.获取文件的后缀名
        //2.1获取原始文件的路径
        String filename = multipartFile.getOriginalFilename();
        //2.2截取字符串获得后缀名
        String name = filename.substring(filename.lastIndexOf("."));
        if (!chickFilter(name)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文件后缀名不符合");
        }
        //3.获取用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //4.将文件上传到oss上
        //4.1先生成UUID加后缀名生成id,把“，”替换为空字符
        String uidname = UUID.randomUUID().toString().replaceAll("-", "");

        try {
            //4.2需要三个参数，参数一：上传到哪个文件夹 参数二：文件在oss中的名称 参数三：要上传文件的输入流
            String store = fileStorageService.store(prefix, uidname + name, multipartFile.getInputStream());
            //5.向素材表中添加数据
            WmMaterial material = new WmMaterial();
            //这是登录用户的id
            material.setUserId(user.getId());
            material.setUrl(store);
            material.setType((short)0);
            //0代表未收藏，1代表收藏
            material.setIsCollection((short)0);
            material.setCreatedTime(new Date());
            //保存到实体类中
            save(material);
            //6.返回封装的结果
            return ResponseResult.okResult();

        } catch (IOException e) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文件上传失败");
        }
        return null;
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //1.参数检验
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //2.通过封装的工具类，获取当前用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //3.执行分页查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        //4.其他查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        //4.1判断素材状态是否收藏
        if (WemediaConstants.COLLECT_MATERIAL.equals(dto.getIsCollection())){
            //状态为1时进行查询
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //4.2只能查询当前登录用户上传的信息
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //4.3按照发布时间降序排序
        wrapper.orderByAsc(WmMaterial::getCreatedTime);
        //5.封装查询结果
        IPage<WmMaterial> result = this.page(page, wrapper);
        List<WmMaterial> records = result.getRecords();
        //遍历
        for (WmMaterial record : records) {
            //图片需要加上前缀访问路径
            record.setUrl(webSite+record.getUrl());
        }
        //5.返回的结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), records);
        return responseResult;
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    //依赖注入
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delete(Integer id) {
        //1.校验参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不存在");
        }
        //2.根据id查询素材
        WmMaterial material = this.getById(id);
        //2.1查看是否有素材
        if (material==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在");
        }
        //3.判断素材是否被引用
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材被引用了");
        }
        //4.从数据库中删除对应素材
        this.removeById(id);
        //5.从oss中删除对应的数据
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    /**
     * 图片的收藏与取消
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updatePictur(Integer id, Short type) {
        //1.参数校验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //2.查看图片状态,是否存在
        WmMaterial material = this.getById(id);
        if (material==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在");
        }
        //3.获取用户信息
        Integer wmid = WmThreadLocalUtils.getUser().getId();
        //如果用户id不一致
        if (!material.getUserId().equals(wmid)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"只能收藏自己上传的素材");
        }
        material.setIsCollection(type);
        updateById(material);
        return ResponseResult.okResult();
    }

    /**
     * 配置文件后缀名分类查找
     * @param name
     * @return
     */
    private boolean chickFilter(String name) {
        List<String> asList = Arrays.asList(".jpg", ".png", ".gif");
        //遍历
        for (String list : asList) {
            if (list.equals(name)){
                return true;
            }
        }
        return false;
    }
}
